package com.camartsApp.service.impl;


import com.camartsApp.dto.PhotoLikedDTO;
import com.camartsApp.dto.UserProfileDTO;
import com.camartsApp.entity.Photo;
import com.camartsApp.entity.Post;
import com.camartsApp.service.UserInfoService;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import com.camartsApp.common.UserInfoVO;
import com.camartsApp.mapper.UserInfoMapper;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResultVO getAvatarById(Long userId) {
        String avatar = userMapper.selectAvatarById(userId);
        return Response.OkByData(avatar);
    }

    @Override
    public ResultVO getNicknameById(Long userId) {
        String nickname = userMapper.selectNicknameById(userId);
        return Response.OkByData(nickname);
    }

    @Override
    public ResultVO getFollowingCountById(Long userId) {
        Long count = userMapper.selectFollowingCountById(userId);
        //hidecount为查询状态为4的用户的数量
//        Long hideCount=userMapper.countFollowingByUserIdAndStatus(userId,4) ;
//        Long hideCount2=userMapper.countFollowingByUserIdAndStatus(userId,2) ;
//        return Response.OkByData(count-hideCount-hideCount2);
        return Response.OkByData(count);
    }

    @Override
    public ResultVO getFollowersCountById(Long userId) {
        Long count = userMapper.selectFollowersCountById(userId);
//        Long hideCount=userMapper.countFollowersByUserIdAndStatus(userId,4) ;
//        Long hideCount2=userMapper.countFollowersByUserIdAndStatus(userId,2) ;
//        return Response.OkByData(count-hideCount-hideCount2);
        return Response.OkByData(count);
    }

    @Override
    public ResultVO getLikesCountById(Long userId) {
        Long count = userMapper.selectLikesCountById(userId);
        return Response.OkByData(count);
    }

    @Override
    public ResultVO getSignatureById(Long userId) {
        String signature = userMapper.selectSignatureById(userId);
        return Response.OkByData(signature);
    }

    @Override
    public ResultVO getStatusById(Long userId) {
        Byte status = userMapper.selectStatusById(userId);
        return Response.OkByData(status);
    }

    @Override
    public ResultVO setHideFollowing(Long userId, boolean isPublic) {
        userMapper.updateHideSetting(userId, "hide_following", isPublic);
        return Response.OkByMsg("关注列表设置成功");
    }

    @Override
    public ResultVO setHideFollowers(Long userId, boolean isPublic) {
        userMapper.updateHideSetting(userId, "hide_followers", isPublic);
        return Response.OkByMsg("粉丝列表设置成功");
    }

    @Override
    public ResultVO setHideWorks(Long userId, boolean isPublic) {
        userMapper.updateHideSetting(userId, "hide_works", isPublic);
        return Response.OkByMsg("作品列表设置成功");
    }

    @Override
    public ResultVO setHideLikes(Long userId, boolean isPublic) {
        userMapper.updateHideSetting(userId, "hide_likes", isPublic);
        return Response.OkByMsg("喜欢的作品列表设置成功");
    }

    @Override
    public ResultVO getHideFollowingStatus(Long userId) {
        Boolean status = userMapper.getHideSetting(userId, "hide_following");
        return Response.OkByData(status != null && status);
    }

    @Override
    public ResultVO getHideFollowersStatus(Long userId) {
        Boolean status = userMapper.getHideSetting(userId, "hide_followers");
        return Response.OkByData(status != null && status);
    }

    @Override
    public ResultVO getHideWorksStatus(Long userId) {
        Boolean status = userMapper.getHideSetting(userId, "hide_works");
        return Response.OkByData(status != null && status);
    }

    @Override
    public ResultVO getHideLikesStatus(Long userId) {
        Boolean status = userMapper.getHideSetting(userId, "hide_likes");
        return Response.OkByData(status != null && status);
    }

    @Override//批量获取用户信息
    public List<UserInfoVO> getUserInfoListByIds(List<Long> userIds) {
        return userIds.stream().map(userId -> {
            UserInfoVO vo = new UserInfoVO();
            vo.setId(userId);
            vo.setAvatar(userMapper.selectAvatarById(userId));
            vo.setNickname(userMapper.selectNicknameById(userId));
            vo.setSignature(userMapper.selectSignatureById(userId));
            vo.setFollowingCount(userMapper.selectFollowingCountById(userId));
            vo.setFollowersCount(userMapper.selectFollowersCountById(userId));
            vo.setLikesCount(userMapper.selectLikesCountById(userId));
            return vo;
        }).toList();
    }


//    @Override
//    public ResultVO getMyPhotos(Long userId) {
//        List<Photo> photos = userMapper.selectPhotosByUserId(userId);
//        return Response.OkByData(photos);
//    }


    @Override
    public ResultVO getPhotosByUserId(Long userId) {
        List<Photo> photos = userMapper.selectPhotosByUserId(userId);
        System.out.println(photos + "here");
        return Response.OkByData(photos);
    }



    @Override
    public ResultVO isSelf(Long currentUserId, Long targetUserId) {
        boolean isSelf = currentUserId.equals(targetUserId);
        return Response.OkByData(isSelf);
    }

    @Override
    public ResultVO deletePhoto(Long userId, Long photoId) {
        int rows = userMapper.updatePhotoStatusByIdAndUserId(userId, photoId);
        // mongo 删除相应的帖子，软删除状态设为3
        if (rows > 0) {
            try {
                // 构建查询条件，查找 imageId 等于 photoId 的帖子
                Query postQuery = new Query(Criteria.where("imageId").is(photoId.intValue()));
                Update postUpdate = new Update().set("status", 3).set("updateTime", new Date()).set("isDelete",  true);


                // 更新帖子状态
                UpdateResult postResult = mongoTemplate.updateFirst(postQuery, postUpdate, "posts");
                System.out.println("--- [DEBUG] Mongo update post status to 3. Modified count: " + postResult.getModifiedCount() + " ---");
                
                try {
                    // 查找被更新的帖子，获取其ID
                    Map postMap = mongoTemplate.findOne(postQuery, Map.class, "posts");
                    if (postMap != null && postMap.get("_id") != null) {
                        Object postId = postMap.get("_id");
                        
                        // 构建查询条件，查找关联到该帖子的所有评论
                        Criteria commentCriteria = new Criteria().orOperator(
                            Criteria.where("post_id").is(postId),
                            Criteria.where("post_id").is(postId.toString())
                        );
                        Query commentQuery = new Query(commentCriteria);
                        Update commentUpdate = new Update().set("status", 3);
                        
                        // 更新所有关联评论的状态
                        UpdateResult commentResult = mongoTemplate.updateMulti(commentQuery, commentUpdate, "comments");
                        System.out.println("--- [DEBUG] Mongo update comments status to 3. Modified count: " + commentResult.getModifiedCount() + " ---");
                    } else {
                        System.out.println("--- [DEBUG] No post found or post has no ID, skipping comment updates ---");
                    }
                } catch (Exception e) {
                    // 记录异常但不影响主流程
                    System.err.println("--- [ERROR] Failed to update comment status: " + e.getMessage() + " ---");
                    e.printStackTrace();
                }
            } catch (Exception e) {
                // 记录异常但不影响主流程
                System.err.println("--- [ERROR] Failed to update post status: " + e.getMessage() + " ---");
                e.printStackTrace();
            }

            return Response.OkByMsg("照片删除成功");
        } else {
            return Response.FailResultByMsg("照片不存在或无权限操作");
        }
    }



    @Override
    public ResultVO getLikedPhotosByLoginUser(Long userId) {
        List<Long> photoIds = userMapper.selectLikedPhotoIdsByUserId(userId);
        if (photoIds == null || photoIds.isEmpty()) {
            return Response.OkByData(List.of());
        }
        List<PhotoLikedDTO> photos = userMapper.selectPhotoDetailsByIds(photoIds);
        return Response.OkByData(photos);
    }

    @Override
    public ResultVO getLikedPhotosByOtherUser(Long userId) {
        List<Long> photoIds = userMapper.selectLikedPhotoIdsByUserId(userId);
        if (photoIds == null || photoIds.isEmpty()) {
            return Response.OkByData(List.of());
        }
        List<PhotoLikedDTO> photos = userMapper.selectPhotoDetailsByIds(photoIds);
        return Response.OkByData(photos);
    }

    @Override
    public ResultVO getUserProfile(Long userId) {
        UserProfileDTO profile = userMapper.selectUserProfileById(userId);
        if (profile == null) {
            return Response.FailResultByMsg("用户不存在");
        }
        return Response.OkByData(profile);
    }









}
